package com.shuai.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.shuai.domain.ai.OpenAIResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 万文帅
 * @date 2023/7/24 19:09
 * @mood happy
 */
@RestController
@RequestMapping("/gpt")
public class ChatGPTController {
    private static final String KEY = "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";

    @PostMapping("/chat")
    public String doChat(@RequestBody String text){
        Map<String,Object> map = new HashMap<>();
        System.setProperty("proxyHost", "127.0.0.1");
        System.setProperty("proxyPort", "7890"); // 代理的端口号
        map.put("model","gpt-3.5-turbo");
        List<Map<String,String>> list = new ArrayList<>();
        list.add(new HashMap<String,String>(){{
            put("role","user");
            put("content",text);
        }});
        map.put("messages",list);
        String jsonStr = JSONUtil.toJsonStr(map);
        HttpRequest post = HttpUtil.createPost("https://api.openai.com/v1/chat/completions");
        post.body(jsonStr);
        post.header("Content-Type","application/json",true);
        post.header("Authorization","Bearer "+ KEY,true);
        HttpResponse execute =post.executeAsync();
        OpenAIResponse openAIResponse = JSONUtil.toBean(execute.body(), OpenAIResponse.class);
        if (openAIResponse == null){
            return "回答失败，请重试！";
        }
        // 返回JSON消息体
        Map<String,String> res = new HashMap<String,String>(){{
            put("content",openAIResponse.getChoices().get(0).getMessage().getContent());
        }};
        return JSONUtil.toJsonStr(res);
    }
}
